﻿#include "AsioIOServicePool.h"
#include <iostream>
using namespace std;

AsioIOServicePool::~AsioIOServicePool() {
    std::cout << "AsioIOServicePool destruct" << endl;
    Stop();  // 确保资源释放
}

void AsioIOServicePool::Init(size_t pool_size) {
    std::lock_guard<std::mutex> lock(_mutex);

    // 1. 创建IO服务和工作对象
    for (size_t i = 0; i < pool_size; ++i) {
        _pool.io_services.emplace_back(std::make_unique<IOService>());
        _pool.works.emplace_back(std::make_unique<Work>(*_pool.io_services[i]));
    }

    // 2. 启动工作线程
    for (size_t i = 0; i < pool_size; ++i) {
        _pool.threads.emplace_back([this, i] {
            _pool.io_services[i]->run();
            });
    }
}

boost::asio::io_context& AsioIOServicePool::GetIOService() {
    std::lock_guard<std::mutex> lock(_mutex);

    // 轮询分配IO服务
    auto& service = *_pool.io_services[_pool.next_index];
    _pool.next_index = (_pool.next_index + 1) % _pool.io_services.size();
    return service;
}

void AsioIOServicePool::Stop() {
    // 1. 释放工作对象允许IO服务退出
    _pool.works.clear();

    // 2. 显式停止所有IO服务 
    for (auto& ios : _pool.io_services) {
        ios->stop();
    }

    // 3. 等待线程结束 
    for (auto& t : _pool.threads) {
        if (t.joinable())  t.join();
    }

    // 4. 清空资源
    _pool.io_services.clear();
    _pool.threads.clear();
    _pool.next_index = 0;
}